<script setup lang="ts">
import { orderDetailsGet, submitBackPost } from '@/services/my.ts';
import type { OrderGoodsList } from '@/types/my.ts';

const props = defineProps<{
  modelValue: boolean;
  orderId: string;
}>();

const afterData = reactive({
  supplierName: '',
  orderCode: '',
  orderId: '',
  supplierId: '',
  afterOrderList: [] as OrderGoodsList[],
});

const $emit = defineEmits(['update:modelValue']);
const show = computed({
  get: () => {
    return props.modelValue;
  },
  set: (value) => {
    $emit('update:modelValue', value);
  },
});
const checkAllPrice = computed(() => {
  return checkList.value.reduce((total, item) => {
    return total + (item.stepNum ?? 1) * item.discountPrice;
  }, 0);
});
watch(show, (value) => {
  if (value) {
    // 弹窗打开时加载数据
    loadData();
  } else {
    // 关闭时清空数据
    state.value = 'one';
    returnReason.value = '';
    checkList.value = [];
    shopChecked.value = false;
  }
});

const checkList = ref<OrderGoodsList[]>([]);
const checkboxGroup = ref<any>(null);
const shopChecked = ref<boolean>(false);
const onCheckBoxClick = () => {
  checkboxGroup.value?.toggleAll(shopChecked.value);
};
const checkedResultChange = (value: string[]) => {
  shopChecked.value = value.length === afterData.afterOrderList.length;
};

// 提交
const onSubmitClick = async () => {
  const params = {
    backPrice: checkAllPrice.value.toFixed(2),
    backRemark: returnReason.value,
    orderCode: afterData.orderCode,
    orderId: afterData.orderId,
    supplierName: afterData.supplierName,
    supplierId: afterData.supplierId,
    subBackGoodsVos: checkList.value.map((item: any) => {
      return {
        amount: item.stepNum,
        unit: item.unit,
        goodsName: item.goodsName,
        goodsImg: item.goodsImg,
        goodsSpec: item.goodsSpec,
        orderGoodsId: item.orderGoodsId,
        backDiscountPrice: item.discountPrice,
        totalDiscountPrice: item.stepNum * item.discountPrice,
        backGoodsPrice: item.price,
        totalPrice: item.stepNum * item.price,
      };
    }),
  };
  const { err, message } = await submitBackPost(params);
  if (err) {
    showToast(err);
    return;
  }
  showToast(message);
  show.value = false;
};

// 下一步
const state = ref('one'); // one 选择 two 备注 three 提交
const returnReason = ref('');
const onNextClick = () => {
  if (state.value === 'one') {
    // 必须选择商品
    if (checkList.value.length === 0) {
      showToast('请选择商品');
      return;
    }
    state.value = 'two';
  } else {
    if (!returnReason.value) {
      showToast('请填写退货原因');
      return;
    }
    state.value = 'three';
  }
};

const onStepChange = async (value: any, order: any) => {
  if (order.amount < value) {
    showToast('超出最大数量');
  }
  if (value < 1) {
    showToast('低于最小数量');
  }
};
const onOverLimit = () => {
  showToast('数量不对');
};
const loadData = async () => {
  const { err, data } = await orderDetailsGet({ orderId: props.orderId });
  if (err) {
    showToast(err);
    return;
  }
  afterData.afterOrderList = data.data.orderGoodsList;
  afterData.supplierName = data.data.supplierName;
  afterData.supplierId = data.data.supplierId;
  afterData.orderId = data.data.orderId;
  afterData.orderCode = data.data.orderCode;
};
</script>

<template>
  <van-popup
    v-model:show="show"
    destroy-on-close
    safe-area-inset-bottom
    closeable
    position="bottom"
  >
    <div v-if="state === 'one'" class="after-pop">
      <div class="pay-text">选择售后商品</div>
      <div class="shop_box">
        <div class="goods_top">
          <div class="goods_check">
            <van-checkbox @click="onCheckBoxClick" v-model="shopChecked"></van-checkbox>
          </div>
          <svg-icon class="shop-icon" icon-class="shop" size="1.4em" />
          <div class="goods_company">{{ afterData.supplierName }}</div>
        </div>
        <van-checkbox-group v-model="checkList" ref="checkboxGroup" @change="checkedResultChange">
          <div class="goods_box" v-for="order in afterData.afterOrderList" :key="order.goodsId">
            <div class="box-top">
              <van-checkbox :name="order" />
              <div class="right">
                <van-image :src="order.goodsImg?.split(',')[0]" round />
                <div class="right_spc">
                  <van-text-ellipsis :content="order.goodsName" />
                  <div class="spc-text">
                    <van-text-ellipsis rows="3" :content="order.goodsSpec" />
                  </div>
                </div>
              </div>
            </div>
            <div class="box-price">
              <div class="price_num">
                <span>单价：￥</span>
                <span class="total-price">{{ `${order.price}` }}</span>
              </div>
              <div class="price-dis">
                <span>折后金额：</span>
                <span>￥</span>
                <span class="dis-text">{{ `${order.discountPrice}` }}</span>
              </div>
            </div>
            <div class="box-step">
              <div class="step-text">退货数量：</div>
              <van-stepper
                v-model="order.stepNum"
                integer
                @change="(value) => onStepChange(value, order)"
                @overlimit="onOverLimit"
                min="1"
                :max="order.amount"
              />
            </div>
          </div>
        </van-checkbox-group>
      </div>
      <van-button color="#E89000" @click="onNextClick" block round text="下一步" />
    </div>

    <div v-if="state === 'two'" class="two-state">
      <div class="pay-text">填写退货原因</div>
      <van-field
        v-model="returnReason"
        rows="6"
        autosize
        type="textarea"
        maxlength="200"
        placeholder="请输入留言"
        show-word-limit
      />
      <div class="two-botton">
        <van-button color="#E89000" @click="onNextClick" block round text="下一步" />
      </div>
    </div>
    <div v-if="state === 'three'" class="three-state">
      <div class="pay-text">确认退货信息</div>
      <div class="goods_box" v-for="order in checkList" :key="order.goodsId">
        <div class="box-top-three">
          <van-image :src="order.goodsImg?.split(',')[0]" />
          <div class="right_spc">
            <van-text-ellipsis :content="order.goodsName" />
            <div class="spc-text">
              <van-text-ellipsis rows="3" :content="order.goodsSpec" />
            </div>
          </div>
          <div class="three-price">
            <div class="price_num curPrice">{{ `￥${order.discountPrice}` }}</div>
            <div class="price_num disPrice">{{ `￥${order.price}` }}</div>
            <div class="price_num amount">{{ `x ${order.stepNum}` }}</div>
          </div>
        </div>
      </div>
      <div class="return-price">
        <span>退款金额:</span>
        <span>￥</span>
        <span class="return-icon">{{ checkAllPrice.toFixed(2) }}</span>
      </div>
      <div class="three-botton">
        <van-field
          v-model="returnReason"
          rows="1"
          readonly
          autosize
          label="退货原因"
          type="textarea"
        />
      </div>

      <van-button color="#E89000" @click="onSubmitClick" block round text="提交" />
    </div>
  </van-popup>
</template>

<style scoped lang="scss">
.after-pop {
  width: 100%;
  background: #ffffff;
  padding: 0 16px;

  .pay-text {
    width: 100%;
    height: 40px;
    font-size: 14px;
    font-weight: 500;
    color: #000000;
    display: flex;
    align-items: center;
  }

  .shop_box {
    width: 100%;

    .goods_top {
      width: 100%;
      height: 40px;
      display: flex;
      align-items: center;

      .shop-icon {
        margin: 0 8px;
      }

      .goods_company {
        font-size: 14px;
        font-weight: 500;
        color: #222222;
      }
    }

    .goods_box {
      width: 100%;
      padding: 8px 0 8px 0;
      border-bottom: 1px solid #1a000020;

      .box-top {
        display: flex;
        align-items: center;

        .right {
          display: flex;

          .van-image {
            width: 88px;
            height: 88px;
            margin: 0 8px;
            border-radius: 8px;
          }

          .right_spc {
            width: 219px;
            font-size: 13px;
            font-weight: 500;
            color: #000000;

            .spc-text {
              width: 100%;
              font-size: 12px;
              font-weight: 400;
              color: #787878;
            }
          }
        }
      }

      .box-price {
        width: 100%;
        font-size: 12px;
        font-weight: 400;
        margin-top: 11px;
        display: flex;
        align-items: center;
        justify-content: flex-end;

        .price_num {
          color: #787878;

          .total-price {
            text-decoration: line-through;
          }
        }

        .price-dis {
          margin-left: 16px;
          color: #222222;

          .dis-text {
            font-size: 16px;
          }
        }
      }

      .box-step {
        width: 100%;
        margin-top: 8px;
        display: flex;
        align-items: center;
        justify-content: flex-end;

        .step-text {
          font-size: 12px;
          font-weight: 400;
          color: #222222;
        }
      }
    }
  }
}

.two-state {
  width: 100%;

  .pay-text {
    width: 100%;
    height: 40px;
    font-size: 14px;
    font-weight: 500;
    color: #000000;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .two-botton {
    width: 100%;
    padding: 0 16px;
  }

  :deep(.van-field__value) {
    background: #f6f6f6;
    border-radius: 4px;
  }
}

.three-state {
  width: 100%;
  background: #ffffff;
  padding: 0 16px;

  .pay-text {
    width: 100%;
    height: 40px;
    font-size: 14px;
    font-weight: 500;
    color: #000000;
    display: flex;
    align-items: center;
  }

  .goods_box {
    width: 100%;
    height: 104px;
    padding: 8px 0 8px 0;

    .box-top-three {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;

      :deep(.van-image) {
        width: 88px;
        height: 88px;
        margin-right: 8px;
        border-radius: 8px;
      }

      .right_spc {
        width: 170px;
        height: 100%;
        font-size: 13px;
        font-weight: 500;
        color: #000000;

        .spc-text {
          width: 100%;
          font-size: 12px;
          font-weight: 400;
          color: #787878;
        }
      }

      .three-price {
        height: 100%;

        .price_num {
          display: flex;
          justify-content: flex-end;
        }

        .curPrice {
          font-size: 14px;
          font-weight: 500;
        }

        .disPrice {
          font-size: 12px;
          font-weight: 400;
          color: #aaaaaa;
          text-decoration: line-through;
        }

        .amount {
          font-size: 10px;
          font-weight: 400;
          color: #aaaaaa;
        }
      }
    }
  }

  .return-price {
    width: 100%;
    height: 25px;
    font-size: 12px;
    font-weight: 400;
    margin: 8px 0;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    color: #222222;

    .return-icon {
      font-size: 16px;
    }
  }

  .three-botton {
    width: 100%;
    background: #f6f6f6;
    border-radius: 4px;

    .van-cell {
      background: #f6f6f6;
    }
  }
}

:deep(.van-stepper__minus) {
  width: 20px;
  height: 20px;
  color: #787878;
  background: transparent;
}

:deep(.van-stepper__plus) {
  width: 20px;
  height: 20px;
  color: #787878;
  background: transparent;
}

:deep(.van-stepper__input) {
  width: 29px;
  height: 18px;
  border-radius: 4px;
  background: #ebebeb;
}

:deep(.van-button--block) {
  height: 40px;
  margin: 20px 0;
}
</style>
